package com.bgq365.study.springboot2.boot02web.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bgq365.study.springboot2.boot02web.service.UserService;
import com.bgq365.study.springboot2.entities.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.Date;
import java.util.List;

@Controller
public class UserController {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private UserService userService;

    /*@GetMapping("/user/{id}")
    public String getUser(@PathVariable String id) {
        Map user = jdbcTemplate.queryForMap("select * from t_user where id =" + id);
        return JSONUtils.toJSONString(user);
    }*/

    @GetMapping("/user/{id}")
    @ResponseBody
    public User findUser(@PathVariable Long id) {
        return userService.getById(id);
    }

    @RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
    @ResponseBody
    public String deleteUser(@PathVariable String id) {
        return "删除User:" + id + ",结果：" + userService.removeById(id) + ",总条数：" + userService.count();
    }

    @RequestMapping(value = "/user", method = RequestMethod.PUT)
    @ResponseBody
    public User editUser(User user) {
        userService.updateById(user);
        return user;
    }

    @PostMapping(value = "/user")
    public String saveUser(User user) {
        user.setCreateTime(new Date());
        userService.save(user);
        return "redirect:/user/list";
    }

    @GetMapping("/user/delete/{id}")
    public String deleteById(@PathVariable String id,
                             @RequestParam(value = "pn", defaultValue = "!") Long pn,
                             RedirectAttributes redirectAttributes) {
        userService.removeById(id);
        redirectAttributes.addAttribute("pn", pn);
        return "redirect:/user/list";
    }

    @GetMapping("/user/list")
    public String pageList(Model model, @RequestParam(value = "pn", defaultValue = "1") Integer pn, Integer size) {
//        List<User> list = userService.list();
//        model.addAttribute("userList", list);

        Page<User> page = new Page<>(pn, 10);
        Page<User> userPage = userService.page(page);
        model.addAttribute("userPage", userPage);
//        model.addAttribute("rows", userPage.getRecords());
//        model.addAttribute("total", userPage.getTotal());
//        model.addAttribute("pn", userPage.getCurrent());
//        model.addAttribute("pages", userPage.getPages());
//        model.addAttribute("total", userPage.getSize());
        return "user";
    }

}
